import toga
from toga.style import Pack
from ssh_forwarder import SSHForwarder

class SSHPortForwardApp(toga.App):
    def __init__(self):
        super().__init__( formal_name='sshui',
             app_id="com.sshui",
             app_name="sshui")
        self.forwarder = SSHForwarder()
        self.is_forwarding = False
        
    def startup(self):
        # 主窗口布局
        main_box = toga.Box(
            style=Pack(direction='column', padding=10)
        )
        
        # 连接设置部分
        connection_box = toga.Box(
            style=Pack(direction='column', padding=10, width=400)
        )
        
        # 主机IP输入框
        host_label = toga.Label('远程主机IP:')
        self.host_input = toga.TextInput(placeholder='例如: 192.168.1.100')
        connection_box.add(host_label)
        connection_box.add(self.host_input)
        
        # SSH端口输入框
        port_label = toga.Label('SSH端口:')
        self.port_input = toga.TextInput(placeholder='默认: 22', value='22')
        connection_box.add(port_label)
        connection_box.add(self.port_input)
        
        # 用户名输入框
        username_label = toga.Label('用户名:')
        self.username_input = toga.TextInput(placeholder='例如: user')
        connection_box.add(username_label)
        connection_box.add(self.username_input)
        
        # 密码输入框
        password_label = toga.Label('密码:')
        self.password_input = toga.PasswordInput()
        connection_box.add(password_label)
        connection_box.add(self.password_input)
        
        # 连接按钮
        self.connect_button = toga.Button(
            '连接',
            on_press=self.connect_ssh,
            style=Pack(padding=5)
        )
        connection_box.add(self.connect_button)
        
        # 端口转发设置部分
        forwarding_box = toga.Box(
            style=Pack(direction='column', padding=10, width=400)
        )
        
        # 转发表标题
        forwarding_label = toga.Label('端口转发表:')
        forwarding_box.add(forwarding_label)
        
        # 转发规则输入框
        self.local_port_input = toga.TextInput(placeholder='本地端口')
        self.remote_host_input = toga.TextInput(placeholder='远程主机地址')
        self.remote_port_input = toga.TextInput(placeholder='远程端口')
        
        forwarding_box.add(toga.Label('本地端口:'))
        forwarding_box.add(self.local_port_input)
        forwarding_box.add(toga.Label('远程主机:'))
        forwarding_box.add(self.remote_host_input)
        forwarding_box.add(toga.Label('远程端口:'))
        forwarding_box.add(self.remote_port_input)
        
        # 添加转发规则按钮
        self.add_rule_button = toga.Button(
            '添加转发规则',
            on_press=self.add_forwarding_rule,
            style=Pack(padding=5)
        )
        forwarding_box.add(self.add_rule_button)
        
        # 转发规则列表
        self.rule_list = toga.Selection()
        forwarding_box.add(self.rule_list)
        
        # 启动/停止转发按钮
        self.toggle_forwarding_button = toga.Button(
            '启动端口转发',
            on_press=self.toggle_forwarding,
            style=Pack(padding=5)
        )
        forwarding_box.add(self.toggle_forwarding_button)
        
        # 状态显示
        self.status_label = toga.Label('状态: 未连接')
        main_box.add(self.status_label)
        
        # 添加各部分到主窗口
        main_box.add(connection_box)
        main_box.add(forwarding_box)
        
        # 创建主窗口
        self.main_window = toga.MainWindow(
            title=self.formal_name,
            size=(500, 600)
        )
        self.main_window.content = main_box
        self.main_window.show()
        
    def connect_ssh(self, widget):
        """连接SSH"""
        hostname = self.host_input.value.strip()
        port = int(self.port_input.value) if self.port_input.value else 22
        username = self.username_input.value.strip()
        password = self.password_input.value
        
        if not all([hostname, username, password]):
            self.status_label.text = '状态: 请填写所有连接信息'
            return
            
        # 连接SSH
        if self.forwarder.connect(hostname, port, username, password):
            self.status_label.text = f'状态: 已连接到 {hostname}'
            self.connect_button.text = '断开连接'
            self.connect_button.on_press = self.disconnect_ssh
        else:
            self.status_label.text = '状态: 连接失败'
            
    def disconnect_ssh(self, widget):
        """断开SSH"""
        self.forwarder.disconnect()
        self.status_label.text = '状态: 已断开连接'
        self.connect_button.text = '连接'
        self.connect_button.on_press = self.connect_ssh
        
    def add_forwarding_rule(self, widget):
        """添加转发规则"""
        local_port = self.local_port_input.value.strip()
        remote_host = self.remote_host_input.value.strip()
        remote_port = self.remote_port_input.value.strip()
        
        if not all([local_port, remote_host, remote_port]):
            self.status_label.text = '状态: 请填写完整的转发规则'
            return
            
        try:
            local_port_int = int(local_port)
            remote_port_int = int(remote_port)
            
            # 添加到转发器
            self.forwarder.add_port_forwarding(local_port_int, remote_host, remote_port_int)
            
            # 更新列表显示
            rule_text = f"本地端口 {local_port} -> 远程主机 {remote_host}:{remote_port}"
            current_rules = list(self.rule_list.items) if hasattr(self.rule_list, 'items') else []
            self.rule_list.items = current_rules + [rule_text]
            
            # 清空输入框
            self.local_port_input.clear()
            self.remote_host_input.clear()
            self.remote_port_input.clear()
            
            self.status_label.text = f'状态: 已添加转发规则 {rule_text}'
        except ValueError:
            self.status_label.text = '状态: 端口号必须是数字'
            
    def toggle_forwarding(self, widget):
        """启动或停止端口转发"""
        if not self.forwarder.is_connected:
            self.status_label.text = '状态: 请先连接SSH'
            return
            
        if not self.is_forwarding:
            # 启动转发
            if self.forwarder.start_forwarding():
                self.is_forwarding = True
                self.toggle_forwarding_button.text = '停止端口转发'
                self.status_label.text = '状态: 端口转发已启动'
            else:
                self.status_label.text = '状态: 启动转发失败'
        else:
            # 停止转发
            self.forwarder.stop_forwarding()
            self.is_forwarding = False
            self.toggle_forwarding_button.text = '启动端口转发'
            self.status_label.text = '状态: 端口转发已停止'

def main():
    return SSHPortForwardApp()

if __name__ == '__main__':
    main().main_loop()